<template>
  <div>
    <div style="width:350px;float:left;">
      <el-scrollbar>
        <basic-container class="tab-content-title">
          <div class="house-gis-main-container">
            <div class="tab-content-title">
              <div class="distinct-title" @click="selectDept('distinct')"><i class="el-icon-map-location" /> {{ distinct }}</div>
            </div>
            <div class="collapse-title" @click="show10 = !show10">
              <span>基本信息</span>
              <i :class="show10 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
            </div>
            <el-collapse-transition>
              <div class="grid-info" v-show="show10">
                <div id="navButtonContainer" class="button-container">
                  <div :class="show101 ? 'on':''" @click="changeTab(1)" >辖区网格</div>
                  <div :class="show102 ? 'on':''" @click="changeTab(2)">辖区房屋</div>
                </div>
                <div id="gridCount" v-show="show101">
                    <div class="chart-title-container">
                        <div class="title">辖区网格统计</div><div class="back-button" @click="resetGridChart('')"></div>
                    </div>
                    <div class="people-count">
                        <div id="gridPieChart" ref="gridPieChart"></div>
                    </div>
                </div>
                <div id="baseHouseCount" v-show="show102">
                    <div class="chart-title-container">
                        <el-select placeholder="选择下级网格" size="mini" v-model="houseChartGridId" style="margin-left: 15px;margin-right: 25px;display: block;" @change="houseChartOptionsSelect">
                          <el-option v-for="(option,index) in houseChartOptions" :key="index" v-bind:label="option.name" :value="option.deptId"></el-option>
                        </el-select>
                    </div>
                    <div class="people-count">
                        <div id="housePieChart" ref="housePieChart"></div>
                    </div>
                </div>
              </div>
            </el-collapse-transition>

            <div class="collapse-title" @click="show20 = !show20">
              <span>房屋查询</span>
              <i :class="show20 ? 'el-icon-arrow-down' :'el-icon-arrow-right'" style="float:right;" ></i>
            </div>
            <el-collapse-transition>
              <div v-show="show20">
                <el-form ref="form" :model="form" label-width="80px!important">
                  <el-form-item label="区域范围">
                    <el-input v-model="areaText" readonly="true" v-on:click.native="selectDept('areaText')" name="gridName" size="mini" clearable></el-input>
                    <input id="treeType" name="treeType"  type="hidden" value="grid"/>
                    <input id="treeId" name="treeType" type="hidden" v-model="areaId"/>
                  </el-form-item>
                  <el-form-item>
                    <el-col :span="11">
                      <el-select placeholder="选择小区" size="mini" v-model="villageName" @change="getBuilding" clearable>
                        <el-option v-for="(option,index) in villages" :key="index" v-bind:label="option.name" :value="option.name" ></el-option>
                      </el-select>
                    </el-col>
                    <el-col class="collapse-line" :span="2"></el-col>
                    <el-col :span="11">
                      <el-select  placeholder="选择楼栋" size="mini" v-model="buildingNo" @change="getUnit" clearable>
                        <el-option v-for="(option,index) in buildings" :key="index" v-bind:label="option.bname" :value="option.ID"></el-option>
                      </el-select>
                    </el-col>

                    <el-col :span="11">
                      <el-select placeholder="选择单元" size="mini" v-model="buildingUnit" @change="getRoom" clearable>
                        <el-option v-for="(option,index) in units" :key="index" v-bind:label="option.name" :value="option.name"></el-option>
                      </el-select>
                    </el-col>
                    <el-col class="collapse-line" :span="2"></el-col>
                    <el-col :span="11">
                      <el-input v-model="houseNumber" placeholder="选择房间" list="roomList" name="roomList" size="mini" clearable></el-input>
                    </el-col>
                  </el-form-item>
                  <el-form-item label="房屋类型">
                    <el-select placeholder="选择房屋类型" size="mini" v-model="houseType">
                      <el-option v-for="(option,index) in houseTypes" :key="index" v-bind:label="option.text" :value="option.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="房屋编号">
                    <el-input v-model.trim="houseCode" size="mini" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="人员姓名">
                    <el-input v-model.trim="houseOwnerName" size="mini" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="证件号码">
                    <el-input v-model.trim="houseOwnerCardNo" size="mini" @mouseWheel='scrollFunc' clearable></el-input>
                  </el-form-item>

                  <el-form-item>
                    <el-button @click="resetForm()" size="mini">重置</el-button>
                    <el-button type="primary" @click="queryButton" size="mini" >搜索</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </el-collapse-transition>
          </div>
        </basic-container>
      </el-scrollbar>
    </div>
    <div style="width:calc(100% - 400px);position: absolute;left:380px;height:calc(100% - 50px)">
        <basic-container>
          <div id="mapDiv" class="map-container">
          </div>
        </basic-container>
    </div>

    <el-dialog
      title="选择定位点"
      ref="mapZtreeDialog"
      append-to-body
      :visible.sync="mapZtreeFlowBox"
      :fullscreen="false"
      custom-class="ztree_dialog"
    >
      <gis-ztree style="height:100%;" v-on:getZtreeMap="getZtreeData($event)" />
    </el-dialog>

    <!-- 实有房屋符合条件查询结果 -->
    <el-dialog
      ref="peopleListDialog"
      append-to-body
      :visible.sync="peopleListWindowFlowBox"
      :fullscreen="false"
      custom-class="people_dialog"
      :class="minimizeClass"
      :modal="modalFlag"
    >
      <template slot="title">
        <div>
          <span>实有房屋符合条件查询结果-<font id="peopleTotalCount">{{peopleCount}}</font>条</span>
          <!-- <div class="minimize-button" @click="miniWindow"><icon class="el-icon-cpu" /></div> -->
        </div>
      </template>
      <div class="people-list-window" id="gridInfoWindow">
        <div class="window">
            <div class="window-content" id="listContent">
                <div class="table-container">
                    <el-table
                    :data="houseData"
                    border
                    style="width: 100%;height:500px;">
                    <el-table-column
                      prop="houseType"
                      label="房屋类型"
                    >
                      <template slot-scope="scope">
                        {{computedToText(scope.row.houseType)}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="addr"
                      label="详细地址"
                    >
                      <template slot-scope="scope">
                        {{truncateAddress(scope.row.addr)}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="birthday"
                      label="房主姓名">
                      <template slot-scope="scope">
                        {{killNull(scope.row.ownerName)}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="birthday"
                      label="联系方式">
                      <template slot-scope="scope">
                        {{killNull(scope.row.ownerMobile)}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="mobile"
                      label="关注类型"
                      width="120"
                    >
                      <template slot-scope="scope">
                        {{killNull(scope.row.ownerMobile)}}
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="gridId"
                      label="GIS">
                      <template slot-scope="scope">
                        <icon class="el-icon-aim" @click="zoomTo(scope.row.id)" :style="scope.row.lat ? 'color:blue':''" />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop=""
                      label="">
                      <template slot-scope="scope">
                        <el-link type="primary" @click="showHouseInfoOnMap(scope.row.id)">详情</el-link>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :total="houseCount"
                  :current-page.sync="page.currentPage"
                  :page-size="page.pageSize"
                  @current-change="handleCurrentChange"
                  style="text-align: center;">
                </el-pagination>
            </div>
        </div>
      </div>
    </el-dialog>

    <!-- 房屋详情 -->
    <el-dialog
      title="房屋详情"
      ref="houseDetailDialog"
      append-to-body
      :visible.sync="houseDetailFlowBox"
      :fullscreen="false"
      custom-class="detail_dialog"
    >
      <house-detail style="height:850px;overflow-y:auto;" :houseId="houseId" />
    </el-dialog>

    <!-- 楼栋详情 -->
    <el-dialog
      title="楼栋详情"
      ref="buildingDetailDialog"
      append-to-body
      :visible.sync="buildingDetailFlowBox"
      :fullscreen="false"
      custom-class="detail_dialog"
    >
      <build-detail style="height:850px;overflow:hidden;" :key="componentKey" :buildingId="buildingId" :buildingUnit="buildingUnits" :houseNumber="houseNumbers" />
    </el-dialog>

  </div>
</template>

<script>
import {loadScript, loadCss,loadModules} from 'esri-loader';
import website from '@/config/website';
import $ from 'jquery';
import "@/assets/css/gis/house.css";

import gisZtree from '@/components/gis/gisZtree'
import buildDetail from '@/components/gis/buildDetail'
import houseDetail from '@/components/gis/houseDetail'

import {getHouseInfoById,getBuildingInfo,getNextGridCount,getHouseCountAndName,getHouseByParam,getDistrictString,getBuilding,getBuildingUnits,getHouseCount} from "@/api/xapply/doubleReal/houseGis"
import {getFocusPeopleCountByBuilding,getHouseByBuildingRent,codeList} from "@/api/xapply/doubleReal/peopleGis"
import {getLoginDept} from '@/api/system/dept'

//引入字典类型
import {HOUSE_TYPE} from '@/config/dictItemArr'

let wkid=website.wkid
let map, graphicsLayer,gridFillSymbol,gridGraphicsLayer,houseGraphicsLayer,buildingGraphicsLayer

let gridPieChartFirstInitFlag = true;
let typename = 'GIS_GRID2';

const echarts = require('echarts');

// let houseType = [{label: "楼房",value: "1"},{label: "平房",value: "2"},{label: "别墅",value: "3"}]

export default {
  name: 'house_gis',
  data(){
    return {
      show10:true,
      show20:true,
      show101:true,
      show102:false,

      form:{},

      distinct: '济南',
      gridId: '100',
      gridLevel: 1,
      deptCode: '3701',

      dictarrlist:{HOUSE_TYPE},

      mapZtreeFlowBox:false,
      peopleListWindowFlowBox:false,

      areaId: "",
      areaText: "",
      houseOwnerName: '',
      houseOwnerCardNo: '',
      houseType: '',
      houseCode: '',
      villageName: '',
      buildingNo: '',
      buildingUnits: '',
      houseNumbers: '',
      buildingUnit: '',
      houseNumber: '',
      houseChartGridId: '',
      villages: [],
      buildings: [],
      units: [],
      rooms: [],
      houseTypes: [],
      houseChartOptions: [],
      houseDetail: {},
      houseList: [],
      buildingId: '',
      buildingIds: '',
      buildingInfo: {},
      pageSize: 8,
      pageNum: 1,
      houseCount: 0,
      currentPage:1,
      houseSearchStatue : 'button',
      houseData:[],
      houseArray:[],
      houseChartData:[],

      buildingDetailFlowBox:false,
      houseDetailFlowBox:false,

      gridCountArr:[],
      searchTableData:[],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
    }
  },

  created(){
    // 数据查询初始化
    this.initData();

    let _this = this
    window.showBuildingDetailWindow = _this.showBuildingDetailWindow
    window.showHouseDetailWindow = _this.showHouseDetailWindow
  },

  mounted() {
    this.initMap();

    console.log("mounted")
  },

  components:{
    gisZtree,
    buildDetail,
    houseDetail
  },
  methods:{
    /**
     *初始化地图
    */
    initMap() {
      let _this = this;
      loadScript({ url: website.InitUrl})
      loadCss(website.CssUrl)
      loadModules([
        "esri/map",
        "esri/layers/ArcGISTiledMapServiceLayer",
        "esri/layers/GraphicsLayer",
        "esri/SpatialReference",
        "esri/geometry/Point",
        "dojo/domReady!"
      ],{ css: true }).then(([
        Map,
        ArcGISTiledMapServiceLayer,
        GraphicsLayer,
        SpatialReference,
        Point
      ]) => {
        map = new Map("mapDiv", {center: website.MapCenterPoint, zoom: 13, logo: false, isDoubleClickZoom: false});
        let myTiledMapServiceLayer = new ArcGISTiledMapServiceLayer(website.BaseMapUrl);
        map.addLayer(myTiledMapServiceLayer);

        graphicsLayer = new GraphicsLayer({id: "graphicsLayer"});
        map.addLayer(graphicsLayer);
        gridGraphicsLayer = new GraphicsLayer({id: "gridGraphicsLayer"});
        map.addLayer(gridGraphicsLayer);
        houseGraphicsLayer = new GraphicsLayer({id: "houseGraphicsLayer"});
        map.addLayer(houseGraphicsLayer);

        houseGraphicsLayer.on("click",function(e){
          _this.getHouseInfoById(e.graphic.attributes["id"]);
        });

        buildingGraphicsLayer = new GraphicsLayer({id: "buildingGraphicsLayer"});
        map.addLayer(buildingGraphicsLayer);
        buildingGraphicsLayer.on("click", function (e) {
          let houseType = e.graphic.attributes["houseType"];
          let id = e.graphic.attributes["id"];
          _this.buildingId = id;
          switch (houseType) {
            case "1":
              _this.showBuildingInfoOnMap(id);
              break;
            default:
              _this.showHouseInfoOnMap(id);
              break;
          }
        });

        map.on("load", function () {
            let point = new Point(website.MapCenterPoint[0], website.MapCenterPoint[1], new SpatialReference(wkid));
            console.log("point:",point)
            map.centerAndZoom(point,11);
            map.infoWindow.resize(400, 300);

            //获取网格数量
            _this.getGridCount();
        });
        map.on("extent-change", function () {
            // mapExtentChange(e);
        });
      });
    },

    //切换
    changeTab(type){
      this.show101 = !this.show101
      this.show102 = !this.show102

      if(type == 2){
        //辖区房屋
        //if(!this.houseChartData)
          this.getHouseData()
      }else{
        //辖区网格
        if(!this.gridCountArr)
          this.getGridCount()
      }
    },

    //辖区房屋选择事件
    houseChartOptionsSelect(){
      this.getHouseData(this.houseChartGridId)
    },

    /*双实房屋左上角-选择网格*/
    selectDept() {
      this.mapZtreeFlowBox = true

    },

    //选择定位点后的回调操作
    getZtreeData(data){
      this.areaText = data.gridName
      this.areaId = data.gridId

      this.mapZtreeFlowBox = false

      this.villages = [];
      this.buildings = [];
      this.units = [];
      this.rooms = [];

      this.villageName = "";
      this.buildingNo = "";
      this.buildingUnit = "";
      this.houseNumber = "";

      //获取地区信息
      getDistrictString(this.areaId).then(result=>{
        if(result.data)
          this.villages = result.data;
      })
    },

    //查询事件
    queryButton(){
      this.houseSearchStatue = "button";
      this.currentPage = 1;
      this.pageNum = '1';

      this.searchHouse();
    },

    // 根据筛选条件查询人口信息
    searchHouse() {
      let data = {
        gridId: this.areaId,
        houseOwnerName: this.houseOwnerName,
        houseOwnerCardNo: this.houseOwnerCardNo,
        houseType: this.houseType,
        houseCode: this.houseCode,
        villageName: this.villageName,
        buildingNo: this.buildingNo,
        buildingUnit: this.buildingUnit,
        houseNumber: this.houseNumber,
        size: this.pageSize,
        current: this.pageNum
      };

      getHouseByParam(data).then(result=>{
        this.houseCount = result.data.data.total;
        this.houseArray = result.data.data.records;
        this.addToMap(this.houseArray);
        this.showHouseList(this.houseArray);
      })
    },

    addToMap(arr) {
      loadModules([
        "esri/graphic",
        "esri/symbols/PictureMarkerSymbol",
        "esri/geometry/Point",
        "esri/SpatialReference"
      ], { css: true })
      .then(([Graphic,PictureMarkerSymbol,Point,SpatialReference]) => {
        houseGraphicsLayer.clear();
        let marker = new PictureMarkerSymbol("/img/building.png", 32, 32);
        for (let i = 0; i < arr.length; i++) {
          if (!arr[i].lng)
            continue;

          let obj = arr[i];
          let point = new Point(parseFloat(obj.lng), parseFloat(obj.lat), new SpatialReference(wkid));
          let graphic = new Graphic(point, marker, obj);
          houseGraphicsLayer.add(graphic);
          console.log("addtomap+end")
        }
      });
    },

    showHouseList(arr) {
      this.houseData = arr

      this.peopleListWindowFlowBox = true
    },

    //初始化组织信息
    initData() {
      //加载组织数据
      getLoginDept().then(res=>{
        this.deptCode = res.data.deptCode
        this.distinct = res.data.deptName
        this.gridId = res.data.id
      })

      //加载系统类型
      codeList(HOUSE_TYPE.value).then(result=>{
        let cloneResult = JSON.parse(JSON.stringify(result.data))
        //插入头部一个空值
        cloneResult.unshift({value:'',text:'无'})

        // this.houseType = cloneResult
        this.houseTypes = cloneResult

        // let textV = this.houseType[0].text

        // result.data.unshift({value:'',text:textV})

        // this[HOUSE_TYPE.value] = result.data
      })
    },

    //获取房屋信息
    getHouseInfoById(id) {

      getHouseInfoById(id).then(result=>{
        this.houseDetail = result.data;
        this.houseDetail.houseType === '1' ? this.showBuildingHouseInfoOnMap() : this.showSingleHouseInfoOnMap();
      })
    },

    //所楼栋信息定位到地图
    showBuildingHouseInfoOnMap() {

      getBuildingInfo(this.houseDetail.buildingId).then(result=>{
        this.buildingInfo = result.data;

        //获取楼栋人员信息
        getFocusPeopleCountByBuilding(this.buildingId).then(res=>{
          this.buildingFocusPeopleList = res.data;

          getHouseByBuildingRent(this.buildingId).then(re=>{
            this.buildingRentList = re.data;


            loadModules([
              "esri/geometry/Point",
              "esri/SpatialReference"
            ], { css: true })
            .then(([Point,SpatialReference]) => {
              let _this = this
              let obj = _this.houseDetail;

              if (!obj.lng)
                  return;
              map.infoWindow.resize(400, 300);
              // houseGraphicsLayer.clear();

              let statueStr = "";
              if (_this.houseDetail.isRent === "Y") {
                  statueStr += "<img width='20' height='20' src='/img/rent.png'>";
              }
              if (_this.houseDetail.isDanger === "Y")
                  statueStr += "<img width='20' height='20' src='/img/danger.png'>";

              let content = "<div class='house-detail-map' style='height: 220px;'>" +
                "<div class='top-nav'>" +
                "<div class='nav-house active' onclick='$(\".nav-content\").hide();$(\".nav-house\").show();$(this).addClass(\"active\").siblings().removeClass(\"active\");' >房屋详情</div>" +
                "<div data-class='.nav-building' onclick='$(\".nav-content\").hide();$(\".nav-building\").show();$(this).addClass(\"active\").siblings().removeClass(\"active\");'>楼栋详情</div>" +
                "</div>" +
                "<div class='nav-content nav-house'>" +
                "<table>" +
                "<tr><td>小区名称：</td><td>" + _this.killNull(obj.communityName) + "</td></tr>" +
                "<tr><td>房间地址：</td><td>" + _this.killNull(obj.houseAddr) + "</td></tr>" +
                "<tr><td>房主姓名：</td><td>" + _this.killNull(obj.houseOwnerName) + "</td></tr>" +
                "<tr><td>联系方式：</td><td>" + _this.killNull(obj.houseOwnerMobile) + "</td></tr>" +
                "<tr><td>联系地址：</td><td>" + _this.killNull(obj.houseAddr) + "</td></tr>" +
                "</table>" +
                "<div><div class='top-img'>" + statueStr + "</div><div class='detail-button-container'><div class='detail-button' onclick='showHouseDetailWindow(\"" + obj.id + "\")'>详情</div></div>" +
                "</div>" +
                "</div>" +
                "<div class='nav-content nav-building'>" +
                "<table>" +
                "<tr><td>小区名称：</td><td>" + _this.killNull(_this.buildingInfo.buildingInfo.communityName) + "</td></tr>" +
                "<tr><td>实有户数：</td><td>" + _this.killNull(_this.buildingInfo.houseList.length) + "</td></tr>" +
                "<tr><td>实住人口：</td><td>" + _this.killNull(_this.buildingInfo.peopleCount) + "</td></tr>" +
                "<tr><td>有无特殊人员：</td><td>" + (_this.buildingFocusPeopleList.length > 0 ? '是' : '否') + "</td></tr>" +
                "<tr><td>出租房屋数量：</td><td>" + _this.killNull(_this.buildingRentList.length) + "</td></tr>" +
                "<tr><td>小区地址：</td><td>" + _this.killNull(_this.buildingInfo.buildingInfo.addrDetail) + "</td></tr>" +
                "</table>" +
                "<div><div class='top-img'></div><div class='detail-button-container'><div class='detail-button' onclick='showBuildingDetailWindow(\"" + _this.buildingInfo.buildingInfo.id + "\",\"" + obj.buildingUnit + "\",\"" + obj.houseNumber + "\")'>详情</div></div>" +
                "</div>" +
                "</div>" +
                "</div>";

              map.infoWindow.setTitle(_this.killNull(_this.buildingInfo.buildingInfo.communityName) + _this.killNull(_this.buildingInfo.buildingInfo.buildingName) + "--" + _this.killNull(_this.buildingInfo.buildingInfo.buildingLeaderName) + "(楼栋长)");
              map.infoWindow.setContent(content);

              let point = new Point(parseFloat(obj.lng), parseFloat(obj.lat), new SpatialReference(wkid));

              // var marker = new esri.symbol.PictureMarkerSymbol("../img/bungalow.png", 32, 32);
              // var graphic = new esri.Graphic(point, marker, obj);
              // houseGraphicsLayer.add(graphic);
              map.infoWindow.show(point);
              map.getZoom() < 7 ? map.centerAndZoom(point, 7) : map.centerAt(point);
            })
          })
       })
      })
    },

    //所房屋信息定位到地图
    showSingleHouseInfoOnMap() {
      loadModules([
        "esri/geometry/Point",
        "esri/SpatialReference",
        "esri/symbols/PictureMarkerSymbol",
        "esri/graphic"
      ], { css: true })
      .then(([Point,SpatialReference,PictureMarkerSymbol,Graphic]) => {
        let _this = this
        let obj = _this.houseDetail;
        if (!obj.lng)
          return;

        map.infoWindow.resize(400, 300);
        // houseGraphicsLayer.clear();
        let statueStr = "";
        let bakImg = "";
        if (_this.houseDetail.isRent === "Y") {
          statueStr += "<img width='20' height='20' src='/img/rent.png'>";
        }
        if (_this.houseDetail.isDanger === "Y")
          statueStr += "<img width='20' height='20' src='/img/danger.png'>";
        if (_this.houseDetail.houseType === "30")
          bakImg = "style='background:url(\"/img/villaDetail.png\") no-repeat center;'";

        let content = "<div class='house-detail-map'>" +
            "<div class='nav-content nav-house'>" +
            "<table>" +
            "<tr><td>小区名称：</td><td>" + _this.killNull(obj.communityName) + "</td></tr>" +
            "<tr><td>房间地址：</td><td>" + _this.killNull(obj.houseAddr) + "</td></tr>" +
            "<tr><td>房主姓名：</td><td>" + _this.killNull(obj.houseOwnerName) + "</td></tr>" +
            "<tr><td>联系方式：</td><td>" + _this.killNull(obj.houseOwnerMobile) + "</td></tr>" +
            "<tr><td>联系地址：</td><td>" + _this.killNull(obj.houseAddr) + "</td></tr>" +
            "</table>" +
            "<div><div " + bakImg + " class='top-img'>" + statueStr + "</div><div class='detail-button-container'><div class='detail-button' onclick='showHouseDetailWindow(\"" + obj.id + "\")'>详情</div></div>" +
            "</div>" +
            "</div>" +
            "<div class='nav-content nav-building'>" +
            "</div>" +
            "</div>";

        map.infoWindow.setTitle("房屋详情");
        map.infoWindow.setContent(content);
        let point = new Point(parseFloat(obj.lng), parseFloat(obj.lat), new SpatialReference(wkid));

        var marker = new PictureMarkerSymbol("/img/bungalow.png", 32, 32);
        var graphic = new Graphic(point, marker, obj);
        houseGraphicsLayer.add(graphic);
        map.infoWindow.show(point);
        // map.getZoom() < 7 ? map.centerAndZoom(point, 7) : map.centerAt(point);
      })
    },

    //初始化楼栋信息到地图
    showBuildingInfoOnMap(id) {

      //获取楼栋基本信息
      getBuildingInfo(id).then(result=>{
        this.buildingInfo = result.data;

        getFocusPeopleCountByBuilding(this.buildingId).then(res=>{
          this.buildingFocusPeopleList = res.data;

          getFocusPeopleCountByBuilding(this.buildingId).then(re=>{
            this.buildingRentList = re.data

            loadModules([
              "esri/geometry/Point",
              "esri/SpatialReference"
            ], { css: true })
            .then(([Point,SpatialReference]) => {
              let _this = this

              let content = "<div class='house-detail-map' style='height: 195px;'>" +
                    "<div class='nav-content nav-building' style='display: block;'>" +
                    "<table>" +
                    "<tr><td>小区名称：</td><td>" + _this.killNull(_this.buildingInfo.buildingInfo.communityName) + "</td></tr>" +
                    "<tr><td>实有户数：</td><td>" + _this.killNull(_this.buildingInfo.houseList.length) + "</td></tr>" +
                    "<tr><td>实住人口：</td><td>" + _this.killNull(_this.buildingInfo.peopleCount) + "</td></tr>" +
                    "<tr><td>有无特殊人员：</td><td>" + (_this.buildingFocusPeopleList.length > 0 ? '是' : '否') + "</td></tr>" +
                    "<tr><td>出租房屋数量：</td><td>" + _this.buildingRentList.length + "</td></tr>" +
                    "<tr><td>小区地址：</td><td>" + _this.killNull(_this.buildingInfo.buildingInfo.addrDetail) + "</td></tr>" +
                    "</table>" +
                    "<div><div class='top-img'></div><div class='detail-button-container'><div class='detail-button' onclick='showBuildingDetailWindow(\"" + _this.buildingInfo.buildingInfo.id + "\")'>详情</div></div>" +
                    "</div>" +
                    "</div>" +
                    "</div>";
                map.infoWindow.setTitle(_this.buildingInfo.buildingInfo.communityName + _this.buildingInfo.buildingInfo.buildingName + "--" + _this.buildingInfo.buildingInfo.buildingLeaderName + "(楼栋长)");
                map.infoWindow.setContent(content);
                var point = new Point(parseFloat(_this.buildingInfo.buildingInfo.lng), parseFloat(_this.buildingInfo.buildingInfo.lat), new SpatialReference(wkid));
                map.infoWindow.show(point);
                // map.centerAt(point);
            })
          })
        })
      })
    },

    showHouseInfoOnMap(id) {
      this.getHouseInfoById(id);
      this.peopleListWindowFlowBox = false
    },

    //获取网格数量
    getGridCount() {

      getNextGridCount().then(result=>{
        this.gridCountArr = result.data;

        //初始化图表
        this.initChart(result.data);

        this.changeHouseTypeCountSelect();
        // getGridListByAttribute();
        this.getHouseCountAndName(this.gridId);
      })
    },

    //显示楼栋详情弹窗
    showBuildingDetailWindow(buildingId,buildingUnit,houseNumber) {
        this.buildingId = buildingId
        this.buildingUnits = buildingUnit
        this.houseNumbers = houseNumber
        this.componentKey += 1;

        console.log("buildinginfo:",buildingId,buildingUnit,houseNumber);

        this.buildingDetailFlowBox = true
    },

    //显示房屋详情弹窗
    showHouseDetailWindow(id) {
      this.houseId = id
      // this.componentKey += 1;
      this.houseDetailFlowBox = true
    },

    //初始化图表
    initChart(data) {
      let legendData = [];
      let dataArr = [];
      for (let i = 0; i < data.length; i++) {
          legendData.push(data[i].name);
          dataArr.push(data[i].value);
      }
      let gridPieChart = echarts.init(this.$refs.gridPieChart, 'infographic');
      // if (gridPieChart == undefined)
      //     gridPieChart = echarts.init(this.$resf.gridPieChart, 'infographic');
      // else
      //     gridPieChart.clear();

      let option = {
        title: {
            show: false
        },
        grid: {
            left: '10%',
            right: '10%',
            top: '10%',
            bottom: '10%'
        },
        tooltip: {
            show: false,
            trigger: 'item',
            position: 'top',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        toolbox: {
            show: false,
            feature: {
                mark: {show: true},
                dataView: {show: true, readOnly: false},
                magicType: {
                    show: true,
                    type: ['pie', 'funnel'],
                    option: {
                        funnel: {
                            x: '25%',
                            width: '50%',
                            funnelAlign: 'bottom',
                            max: 1548
                        }
                    }
                },
                restore: {show: true},
                saveAsImage: {show: true}
            }
        },
        series: [
            {
                name: '网格数量',
                type: 'pie',
                radius: '75%',
                center: ['50%', '50%'],
                data: data,
                itemStyle: {
                    normal: {
                        label: {
                            show: true,
                            formatter: "{b} , {c}"
                        }, labelLine: {
                            length: 0,
                            length2: 0,
                            show: false
                        }
                    }
                }
            }
        ]
      };

      gridPieChart.setOption(option, true);
      if(gridPieChartFirstInitFlag) {
          gridPieChart.on('click', function (params) {
              if (params.data.deptCode.length >= 9)
                return;
              this.gridId = params.data.deptId;
              this.deptCode = params.data.deptCode;

              //刷新图表
              this.resetGridChart(params.data.deptId);
          });
          gridPieChartFirstInitFlag = false;
      }
    },

    //刷新图表
    resetGridChart(id) {
      console.log("id" + id);

      getNextGridCount(id).then(result=>{
        this.gridCountArr = result.data;
        console.log("统计查询结束时间：" + new Date());

        //初始化图表
        this.initChart(result.data);

        this.changeHouseTypeCountSelect();

        this.getHouseCountAndName(this.gridId);
      })

    },

    //选择小区触发事件
    getBuilding() {
      getBuilding(this.areaId,this.villageName).then(result => {
        this.buildings = result.data;
      })
    },

    //选择楼栋信息时，获取单元信息
    getUnit() {
      getBuildingUnits(this.buildingNo).then(result => {
        this.units = result.data;
      })
    },

    //生成房间信息
    getRoom() {
      for (let i = 0; i < this.units.length; i++) {
        if (this.buildingUnit == this.units[i].name) {
          //initRoomDataList(this.units[i]);
          let rooms = [];
          for (let m = 1; m <= this.units[i].floor; m++) {
              for (let j = 1; j <= this.units[i].number; j++) {
                  rooms.push({name: "" + m + "0" + j});
              }
          }
          this.rooms = rooms;

          return;
        }
      }
    },

    //获取辖区房屋信息
    getHouseData(houseChartGridId) {
      getHouseCount(houseChartGridId ? houseChartGridId : this.gridId).then(result=>{
        this.initHouseChart(result.data);
        this.houseChartData = result.data
      })
    },

    //初始化图表数据
    initHouseChart(data) {
        let legendData = [];
        let dataArr = [];
        for (let i = 0; i < data.length; i++) {
            legendData.push(data[i].name);
            dataArr.push(data[i].value);
        }

        let housePieChart = echarts.init(this.$refs.housePieChart, 'infographic');

        // if (!housePieChart)
        //     housePieChart = echarts.init(this.$refs.housePieChart, 'infographic');
        // else
        //     housePieChart.clear();

        let option = {
            title: {
                show: false
            },
            grid: {
                left: '10%',
                right: '10%',
                top: '10%',
                bottom: '10%'
            },
            tooltip: {
                show: false,
                trigger: 'item',
                position: 'top',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            toolbox: {
                show: false,
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {
                        show: true,
                        type: ['pie', 'funnel'],
                        option: {
                            funnel: {
                                x: '25%',
                                width: '50%',
                                funnelAlign: 'bottom',
                                max: 1548
                            }
                        }
                    },
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            series: [
                {
                    name: '网格数量',
                    type: 'pie',
                    radius: '75%',
                    center: ['50%', '50%'],
                    data: data,
                    itemStyle: {
                        normal: {
                            label: {
                                show: true,
                                color: 'black',
                                formatter: "{b} , {c}"
                            }, labelLine: {
                                color: 'black',
                                length: 0,
                                length2: 0,
                                show: false
                            }
                        }
                    }
                }
            ]
        };
        housePieChart.setOption(option, true);
    },

    //定位到地图
    zoomTo(id) {
      loadModules([
        "esri/geometry/Point",
        "esri/SpatialReference",
        // "esri/graphicsUtils"
      ], { css: true })
      .then(([Point,SpatialReference]) => {
        let _this = this

        if(!id){
            if(!_this.houseArray[0] && !_this.houseArray[0].lng){
                _this.$message.error("未采集位置信息。" )
            }
            else{
                map.centerAt(new Point(parseFloat(_this.houseArray[0].lng), parseFloat(_this.houseArray[0].lat), new SpatialReference(wkid)));
            }
            return;
        }
        for (let i = 0; i < _this.houseArray.length; i++) {
            if (_this.houseArray[i].id == id) {
                if(!_this.houseArray[i] || !_this.houseArray[i].lng){
                    _this.$message.error("未采集位置信息。" )
                }else{
                    map.centerAt(new Point(parseFloat(_this.houseArray[i].lng), parseFloat(_this.houseArray[i].lat), new SpatialReference(wkid)));
                }
                break;
            }
        }
      })
    },

    changeHouseTypeCountSelect() {
      let selectArr = [];
      for (let i = 0; i < this.gridCountArr.length; i++) {
          selectArr.push({name: this.gridCountArr[i].name, value: this.gridCountArr[i].deptId});
      }
      this.houseChartOptions = selectArr;
    },

    getHouseCountAndName(id) {

      getHouseCountAndName(id).then(result=>{
        this.houseCountArr = result.data;
        if (this.deptCode === "")
          this.getGridListByAttribute();
        else
          this.resetMapGrid(this.deptCode);
      })
    },

    getGridListByAttribute(searchTypeName, appendParam) {
      loadModules([
        'esri/symbols/SimpleFillSymbol',
        "esri/symbols/SimpleLineSymbol",
        "esri/Color",
        "esri/geometry/Polygon",
        "esri/graphic",
        "esri/symbols/Font",
        "esri/symbols/TextSymbol",
        // "esri/geometry/Point",
        // "esri/SpatialReference",
        // "esri/graphicsUtils"
      ], { css: true })
      .then(([SimpleFillSymbol,SimpleLineSymbol, Color,Polygon,Graphic,Font,TextSymbol]) => {
        let _this = this
        let layer = searchTypeName ? searchTypeName : typename;
        let baseUrl = website.GeoServerBaseUrl + '/cite/ows?service=WFS&version=1.1.0&request=GetFeature&typename=' + layer + '&outputFormat=json&maxFeatures=80';
        if (appendParam)
          baseUrl += "&cql_filter=" + appendParam;

        console.log("空间查询开始时间：" + new Date());
        $.ajax({
          type: 'post',
          url: baseUrl,
          dataType: 'json',
          success: function (result) {
            console.log("空间查询结束时间：" + new Date());
            let featureSet = result.features;
            gridGraphicsLayer.clear();
            gridFillSymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([66, 0, 0]), 1), new Color([255, 99, 33, 0.15]));

            for (let i = 0; i < featureSet.length; i++) {
              let obj = featureSet[i];
              let polygonJson;
              if (obj.geometry.type === "Polygon") {
                polygonJson = {"rings": obj.geometry.coordinates, "spatialReference": {"wkid": wkid}};
              } else {
                let geoArr = [];
                for (let n = 0; n < obj.geometry.coordinates.length; n++) {
                    geoArr.push(obj.geometry.coordinates[n][0]);
                }
                polygonJson = {"rings": geoArr, "spatialReference": {"wkid": wkid}};
              }

              let polygon = new Polygon(polygonJson);
              let gra = new Graphic(polygon, gridFillSymbol, obj.properties);
              gridGraphicsLayer.add(gra);

              let font = new Font("13px",Font.STYLE_NORMAL, Font.VARIANT_NORMAL,Font.WEIGHT_NORMAL);
              for (let j = 0; j < _this.houseCountArr.length; j++) {
                if (obj.properties.GRID_ID == _this.houseCountArr[j].gridId) {
                  let textSymbol = new TextSymbol(
                    _this.houseCountArr[j].name + ":" + _this.houseCountArr[j].count,
                    font, new Color([0, 33, 99])
                  );
                  let labelPointGraphic = new Graphic(polygon.getExtent().getCenter(), textSymbol);
                  gridGraphicsLayer.add(labelPointGraphic);
                }
              }
            }
            // map.centerAt(esri.graphicsExtent(gridGraphicsLayer.graphics).getCenter());
            // map.setExtent(esri.graphicsExtent(gridGraphicsLayer.graphics), true);
            // map.setExtent(esri.graphicsExtent(gridGraphicsLayer.graphics));
          }
        });
      })
    },

    resetMapGrid(deptCode) {
      let length = deptCode.length + 3;
      let searchTypeName = "GIS_GRID2";
      if (length <= 7)
        searchTypeName = "GIS_GRID2";
      else if (length <= 10)
        searchTypeName = "GIS_GRID3";
      else if (length <= 13)
        searchTypeName = "GIS_GRID4";

      let appendParam = "xzqhdm+LIKE+%27" + deptCode + "%25%27";
      this.getGridListByAttribute(searchTypeName, appendParam);
    },

    killNull(obj){
      return obj ? obj : "";
    },

    truncateAddress(value) {
      return !value ? "" : value.length > 17 ? value.substr(0, 15) + '...' : value;
    },

    //计算属性
    computedToText(type){
      if(this.houseTypes){
          for(let i=0;i<this.houseTypes.length;i++){
              if(this.houseTypes[i].value === type){
                  return this.houseTypes[i].text;
              }
          }
      }
      return "";
    },

    resetForm() {
      this.areaId = "";
      this.areaText = "";
      this.houseOwnerName = "";
      this.houseOwnerCardNo = "";
      this.houseType = "";
      this.houseCode = "";
      this.villageName = "";
      this.buildingNo = "";
      this.buildingUnit = "";
      this.houseNumber = "";
      this.villages = [];
      this.buildings = [];
      this.units = [];
      this.rooms = [];
    },

  }
}
</script>

<style lang="scss" scoped>

</style>
